<template>
	<div>
		<el-button @click="clickReturn">返回</el-button>
		<el-tabs v-model="activeName" @tab-click="handleClick" class="tlTabs">
			<el-tab-pane label="基础信息" name="first">
				<el-form ref="ruleForm" :rules="rules" :model="form" label-width="100px">
					<el-form-item label="专题名称:" prop="name">
						<el-input class="width400" v-model="form.name" placeholder="请输入专题名称"></el-input>
					</el-form-item>
					<el-form-item label="商品描述:">
						<el-input class="width400" type="text" placeholder="请输入内容" v-model="form.description" maxlength="40"
							show-word-limit>
						</el-input>
					</el-form-item>
					<el-form-item label="服务承诺:">
						<el-input class="width400" type="text" placeholder="请输入服务承诺" v-model="form.serveCommit" maxlength="40"
							show-word-limit>
						</el-input>
					</el-form-item>
					<el-form-item label="专题分类:" prop="categoryId">
						<el-select placeholder="请选择专题分类" v-model="form.categoryId" class="width400">
							<el-option v-for="item in subjectCategoryList" :key="item.id" :label="item.name"
								:value="item.id"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="销售价格:" prop="price">
						<el-input class="width400" type="number" placeholder="请输入销售价格" v-model="form.price">
						</el-input>
					</el-form-item>
					<el-form-item label="所属区域" prop="area">
						<div class="row-me row-center">
							<el-cascader :props="props" v-model="form.area" :options="areaData" placeholder="请选择地区" class="width400"
								@change="areaChange"></el-cascader>
							</el-cascader>
						</div>
					</el-form-item>
					<el-form-item label="专题标签">
						<el-select v-model="form.tags" filterable allow-create default-first-option multiple placeholder="请输入专题标签"
							class="width400">
						</el-select>
					</el-form-item>
					<div class="row-me row-center flex-wrap">
						<el-form-item label="虚拟购买人数">
							<el-input placeholder="请输入" v-model="form.virtualNums"></el-input>
						</el-form-item>
						<el-form-item label="自增设定">
							<div class="row-me row-center height40">
								<el-switch v-model="form.isAdd"></el-switch>
								<div class="row-me row-center margin-left10" v-if="form.isAdd">
									<el-input v-model="form.addMin" class="width100"></el-input><span
										class="margin-left5 margin-right5">-</span> <el-input v-model="form.addMax"
										class="width100"></el-input>
								</div>
							</div>
						</el-form-item>
						<el-form-item label="按照">
							<el-select placeholder="请选择" v-model="form.addType">
								<el-option label="每30分钟" :value="1"></el-option>
								<el-option label="每小时" :value="2"></el-option>
								<el-option label="每天" :value="3"></el-option>
							</el-select>
						</el-form-item>
					</div>
					<el-form-item label="上传图片" prop="img">
						<div class="row-me flex-end2">
							<el-image v-if="form.img" class="width80 height80" :src="form.img"
								:preview-src-list="[form.img]"></el-image>
							<el-button type="text" @click="clickImg(1)" class="margin-left10">点击图片库选择</el-button>
						</div>
					</el-form-item>
					<el-form-item label="优惠券">
						<div class="row-me">
							<div class="row-me row-center">
								<el-checkbox v-model="form.newChecked" @change="$forceUpdate()">
									新用户优惠券
									<el-select placeholder="请选择" v-model="form.newPreferentiaId" :disabled="!form.newChecked"
										class="width120 margin-left10" clearable>
										<el-option v-for="item in couponList" :key="item.id" :label="item.name"
											:value="item.id"></el-option>
									</el-select>
								</el-checkbox>
								<el-checkbox v-model="form.oldChecked" @change="$forceUpdate()">
									老用户优惠券<el-select placeholder="请选择" v-model="form.oldPreferentiaId" :disabled="!form.oldChecked"
										class="width120 margin-left10" clearable>
										<el-option v-for="item in couponList" :key="item.id" :label="item.name"
											:value="item.id"></el-option>
									</el-select>
								</el-checkbox>
							</div>
						</div>
					</el-form-item>
					<el-form-item label="限时优惠">
						<el-checkbox v-model="form.timeLimit">
							开启限时优惠
						</el-checkbox>
						<el-date-picker v-if="form.timeLimit" v-model="form.timeDate" type="datetimerange" range-separator="至"
							start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss" @change="dateChange">
						</el-date-picker>
					</el-form-item>
					<el-form-item label="佣金设置" prop="type">
						<el-radio-group v-model="form.type">
							<el-radio :label="2">按比例</el-radio>
							<el-radio :label="1">按金额</el-radio>
						</el-radio-group>
						<br>
						<el-input v-if="form.type==2" placeholder="请输入" class="width300" type="number" v-model="form.value">
							<template slot="append">%</template>
						</el-input>
						<el-input v-if="form.type==1" placeholder="请输入" class="width300" type="number" v-model="form.value">
							<template slot="append">元</template>
						</el-input>
					</el-form-item>
					<el-form-item label="排序">
						<el-input class="width400" v-model="form.sort" placeholder="请输入"></el-input>
					</el-form-item>
					<el-button type="primary" @click="nextTo">下一步</el-button>
				</el-form>
			</el-tab-pane>
			<el-tab-pane label="选择题集" name="second">
				<el-form label-width="100px">
					<el-form-item label="添加专题试卷:" :required="true" label-width="120px">
						<el-button type="text" @click="handleAddCategory">添加分类</el-button>
						<el-table :data="tableDatas" style="width: 100%" border class="newTab" default-expand-all row-key="name"
							:tree-props="{children: 'children', hasChildren: 'hasChildren'}">
							<el-table-column label="试卷名称" align="center" width="300" prop="name">
								<template slot-scope="scope">
									<el-input v-model="scope.row.name" class="width80Per"></el-input>
								</template>
							</el-table-column>
							<el-table-column label="所选试卷" align="center" prop="examName"></el-table-column>
							<el-table-column label="题目数量" prop="questionCount" align="center"></el-table-column>
							<el-table-column label="操作" width="300" align="center">
								<template slot-scope="scope">
									<el-button @click="handleAddCategory(scope.row,1,scope.$index)" type="text"
										v-if="scope.row.parent==0">添加子专题</el-button>
									<el-button @click="handleUp(scope.$index, scope.row)" type="text">上移</el-button>
									<el-button @click="handleDown(scope.$index, scope.row)" type="text">下移</el-button>
									<el-button @click="handleAddCategory(scope.row,2,scope.$index)" type="text">编辑</el-button>
									<el-button @click="deleteRow(scope.$index, scope.row)" type="text">删除</el-button>
								</template>
							</el-table-column>
						</el-table>
						<div class="margin-top20">
							<el-button @click="preTo" type="primary">上一步</el-button>
							<el-button @click="nextTo" type="primary">下一步</el-button>
						</div>
					</el-form-item>
				</el-form>
			</el-tab-pane>
			<el-tab-pane label="详情信息" name="third">
				<el-form :model="form" label-width="100px">
					<el-form-item label="详情信息:">
						<vue-ueditor-wrap v-model="form.specialShow" editor-id="editor" :config="editorConfig"
							:editorDependencies="['ueditor.config.js','ueditor.all.js']" />
					</el-form-item>
					<el-button type="primary" @click="preTo">上一步</el-button>
					<el-button type="primary" @click="handleSave">提交</el-button>
				</el-form>
			</el-tab-pane>
		</el-tabs>

		<!-- 新增编辑分类 -->
		<el-dialog :title="title" :visible.sync="categoryVisible" width="600px">
			<el-form :model="categoryForm">
				<el-form-item label="试卷名称">
					<el-input placeholder="请输入试卷名称" v-model="categoryForm.name" class="width300"></el-input>
				</el-form-item>
				<el-form-item label="选择试卷">
					<el-select placeholder="请选择试卷" filterable v-model="categoryForm.examId" class="width300" @change="examChange"
						clearable>
						<el-option v-for="(item,index) in examTableData" :key="index" :label="item.name"
							:value="item.id"></el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="categoryVisible = false">取 消</el-button>
				<el-button type="primary" @click="clickCategorySave">确 定</el-button>
			</span>
		</el-dialog>

		<imgLibrary ref="imgLibrary" @handleImgOk="handleImgOk"></imgLibrary>
	</div>
</template>

<script>
	import imgLibrary from "@/components/imgLibrary"
	export default {
		components: {
			imgLibrary
		},
		data() {
			let that = this
			const validateOrg = (rule, value, callback) => {
				if (!this.form.area || !this.form.area.length) {
					callback(new Error('所属区域不能为空'))
				} else {
					callback()
				}
			}
			return {
				form: {},
				areaData: [],
				activeName: 'first',
				tabIndex: 0,
				imgIndex: 0,
				editorConfig: {
					serverUrl: process.env.BASE_API + "/file/upload",
					UEDITOR_HOME_URL: '/static/UEditor/',
					toolbarCallback: function(cmd, editor) {
						switch (cmd) {
							case 'insertimage':
								that.imgIndex = 2;
								that.$refs.imgLibrary.show()
								return true;
						}
					}
				},
				props: {
					value: 'id',
					label: 'name',
					checkStrictly: true,
					multiple: true
				},
				tableDatas: [],
				rules: {
					name: {
						required: true,
						message: '请输入专题名称',
						trigger: 'blur'
					},
					price: {
						required: true,
						message: '请输入销售价格',
						trigger: 'blur'
					},
					area: [{
						type: 'array',
						required: true,
						validator: validateOrg
					}],
					img: {
						required: true,
						message: '请上传图片',
						trigger: 'change'
					},
					type: {
						required: true,
						message: '请设置佣金',
						trigger: 'change'
					},
					categoryId: {
						required: true,
						message: '请选择专题分类',
						trigger: 'change',
					}
				},
				index: 1,
				examIndex: 0,
				examTableData: [],
				pageTotal: 0,
				query: {
					pageNumber: 1,
					pageSize: 30
				},
				multipleSelection: [],
				categoryVisible: false,
				title: '',
				categoryForm: {},
				parentIndex: 0,
				couponList: [],
				subjectCategoryList: [],
				isShow: false
			}
		},
		mounted() {
			this.getAllArea()
			this.getPageExamPaper()
			this.getPreferentiaList()
			this.getSubjectCategory()
		},
		methods: {
			show(row) {
				if (row.id) {
					this.getDetail(row.id)
				} else {
					this.form = {}
				}
			},
			//获取专题详情
			async getDetail(id) {
				const res = await this.$get('/admin/specialSubject/getDetail', {
					id
				})
				if (res.code == 1000) {
					this.form = res.data
					this.form.tags = this.form.tags ? this.form.tags.split(',') : []
					this.form.newChecked = this.form.newPreferentiaId ? true : false
					this.form.oldChecked = this.form.oldPreferentiaId ? true : false
					this.form.timeLimit = this.form.timeLimit ? true : false
					if (this.form.addMin && this.form.addMax) {
						this.form.isAdd = true
					}
					this.form.area = this.form.showCity ? JSON.parse(this.form.showCity) : []
					if (this.form.timeStart && this.form.timeEnd) {
						this.form.timeDate = [this.form.timeStart, this.form.timeEnd]
					}
					this.tableDatas = this.form.children || []
					for (var i = 0; i < this.tableDatas.length; i++) {
						this.tableDatas[i].parent = 0
						this.tableDatas[i].parentIndex = i
						this.tableDatas[i].children = this.tableDatas[i].children || []
						if (this.tableDatas[i].children && this.tableDatas[i].children.length != 0) {
							for (var j = 0; j < this.tableDatas[i].children.length; j++) {
								var item = this.tableDatas[i].children[j]
								this.$set(item, 'parentIndex', i)
								this.$set(item, 'childIndex', j)
								this.$set(item, 'examName', item.examPaper ? item.examPaper.name : '')
								this.$set(item, 'questionCount', item.examPaper ? item.examPaper.questionCount : '')
							}
						}
					}
				}
			},
			async getSubjectCategory() {
				const res = await this.$get('/admin/specialSubject/pageSubjectCategory', {
					pageNumber: 1,
					pageSize: 9999
				})
				if (res.code == 1000) {
					this.subjectCategoryList = res.data.list
				}
			},
			clickReturn() {
				this.$emit('handleOk')
			},
			dateChange(val) {
				this.form.timeStart = ''
				this.form.timeEnd = ''
				if (val.length != 0) {
					this.form.timeStart = val[0]
					this.form.timeEnd = val[1]
				}
			},
			async getPreferentiaList() {
				const res = await this.$get('/admin/mall/getPreferentiaList')
				if (res.code == 1000) {
					this.couponList = res.data
				}
			},
			areaChange(val) {
				this.form.province = []
				this.form.city = []
				if (val.length != 0) {
					for (let item of val) {
						if (item[0]) {
							this.form.province.push(item[0])
						}
						if (item[1]) {
							this.form.city.push(item[1])
						}
					}
				}
				this.form.showCity = JSON.stringify(val)
				this.form.province = [...new Set(this.form.province)].toString()
				this.form.city = [...new Set(this.form.city)].toString()
			},
			//下移
			handleDown(i, row) {
				let arr = this.tableDatas
				if (row.parent == 0) {
					arr.splice(row.parentIndex, 1, ...arr.splice(row.parentIndex + 1, 1, arr[row.parentIndex]))
					for (var i = 0; i < arr.length; i++) {
						arr[i].parentIndex = i
					}
				} else {
					arr = this.tableDatas[row.parentIndex].children
					arr.splice(row.childIndex, 1, ...arr.splice(row.childIndex + 1, 1, arr[row.childIndex]))
					for (var i = 0; i < arr.length; i++) {
						arr[i].childIndex = i
					}
				}
				this.tableDatas.push({})
				this.tableDatas.splice(this.tableDatas.length - 1, 1)

			},
			//上移
			handleUp(index, row) {
				let arr = this.tableDatas
				if (row.parent == 0) {
					if (row.parentIndex == 0) return
					arr.splice(row.parentIndex - 1, 1, ...arr.splice(row.parentIndex, 1, arr[row.parentIndex - 1]))
					for (var i = 0; i < arr.length; i++) {
						arr[i].parentIndex = i
					}
				} else {
					if (row.childIndex == 0) return
					arr = this.tableDatas[row.parentIndex].children
					arr.splice(row.childIndex - 1, 1, ...arr.splice(row.childIndex, 1, arr[row.childIndex - 1]))
					for (var i = 0; i < arr.length; i++) {
						arr[i].childIndex = i
					}
				}
				this.tableDatas.push({})
				this.tableDatas.splice(this.tableDatas.length - 1, 1)
			},
			examChange(id) {
				this.categoryForm.examName = ''
				this.categoryForm.questionCount = ''
				this.$forceUpdate()
				for (let item of this.examTableData) {
					if (item.id == id) {
						this.categoryForm.examName = item.name
						this.categoryForm.questionCount = item.questionCount
					}
				}
			},
			//分类确认
			clickCategorySave() {
				if (this.$.isEmpty(this.categoryForm.name)) {
					this.$message.warning('请输入试卷名称!')
					return
				}
				if (this.isShow || this.categoryForm.parent == 0) {
					if (this.isShow) {
						if (this.$.isEmpty(this.categoryForm.examId)) {
							this.$message.warning('请选择试卷!')
							return
						}
					}
					if (this.categoryForm.isChild) { //添加子专题
						this.tableDatas[this.parentIndex].examId = ''
						this.tableDatas[this.parentIndex].examName = ''
						if (this.tableDatas[this.parentIndex].children && Array.isArray(this.tableDatas[this.parentIndex]
								.children)) {
							this.tableDatas[this.parentIndex].children.push({
								name: this.categoryForm.name,
								examId: this.categoryForm.examId,
								examName: this.categoryForm.examName,
								questionCount: this.categoryForm.questionCount,
								childIndex: this.tableDatas[this.parentIndex].children.length,
								parentIndex: this.tableDatas[this.parentIndex].parentIndex
							})
							this.tableDatas.push({})
							this.tableDatas.splice(this.tableDatas.length - 1, 1)
						}
					} else { //编辑
						if (this.tableDatas[this.parentIndex].children.length != 0 && this.isShow) {
							let obj = this.tableDatas[this.parentIndex].children[this.examIndex]
							this.$set(obj, 'name', this.categoryForm.name)
							this.$set(obj, 'examName', this.categoryForm.examName)
							this.$set(obj, 'questionCount', this.categoryForm.questionCount)
							this.$set(obj, 'examId', this.categoryForm.examId)
						} else {
							let parentObj = this.tableDatas[this.parentIndex]
							this.$set(parentObj, 'examId', this.categoryForm.examId)
							this.$set(parentObj, 'examName', this.categoryForm.examName)
							this.$set(parentObj, 'questionCount', this.categoryForm.questionCount)
							this.$set(parentObj, 'name', this.categoryForm.name)
						}
					}
					for (let item of this.tableDatas) {
						item.questionCount = 0
						if (item.children && item.children.length != 0) {
							for (let val of item.children) {
								item.questionCount += val.questionCount
							}
						}
					}
				} else {
					//新增
					this.tableDatas.push({
						...this.categoryForm,
						parent: 0,
						children: [],
						parentIndex: this.tableDatas.length
					})
				}
				this.categoryVisible = false
			},
			//添加分类
			handleAddCategory(row, type = 0, index = 0) {
				this.isShow = false
				if (row.name) {
					this.isShow = true
					this.parentIndex = row.parentIndex
					this.title = '编辑'
					this.categoryForm = JSON.parse(JSON.stringify(row))
					if (type == 1) {
						this.title = '新增'
						this.categoryForm.isChild = true
						this.categoryForm.name = ''
						this.categoryForm.examId = ''
						this.categoryForm.examName = ''
					} else {
						this.categoryForm.isChild = false
						this.examIndex = row.childIndex
						if (this.categoryForm.parent == 0) {
							this.isShow = false
						} else {
							this.isShow = true
						}
					}
				} else {
					this.title = '新增'
					this.categoryForm = {}
					this.parentIndex = 0
					this.categoryForm.isChild = false
				}
				this.categoryVisible = true
			},
			// 获取试卷
			async getPageExamPaper() {
				const res = await this.$post(
					`/admin/examPaper/pageExamPaperAll?pageNumber=1&pageSize=9999&roleType=2`, {
						roleType: 2
					})
				const res2 = await this.$post(
					`/admin/examPaper/pageExamPaperAll?pageNumber=1&pageSize=9999&roleType=1&type=2`, {
						roleType: 1,
						type: 2
					})
				this.examTableData = [...res.data.list, ...res2.data.list]
			},
			//添加子专题
			addExam() {
				this.index++
				this.tableDatas[0].children.push({
					id: this.index,
					examName: ''
				})
			},
			//提交
			async handleSave() {
				if (this.tableDatas && this.tableDatas.length == 0) {
					this.$message.warning('请选择题集!')
					return
				}
				if (this.tableDatas && this.tableDatas.length != 0) {
					this.form.children = this.tableDatas
					if (this.$.isEmpty(this.form.id)) {
						if (this.form.children.length != 0) {
							for (let item of this.form.children) {
								if (item.children && item.children.length != 0) {
									for (let val of item.children) {
										val.id = undefined
									}
								}
								item.id = undefined
							}
						}
					}
				}
				this.form.tags = this.form.tags ? this.form.tags.toString() : ''
				this.form.userType = 2
				this.form.timeLimit = this.form.timeLimit ? 1 : 0
				const res = await this.$post('/admin/specialSubject/addSubject', this.form)
				if (res.code == 1000) {
					this.$message.success('操作成功')
					this.clickReturn()
				}
			},
			//移除
			deleteRow(index, row) {
				if (row.parent == 0) {
					this.tableDatas.splice(row.parentIndex, 1);
					for (var i = 0; i < this.tableDatas.length; i++) {
						this.tableDatas[i].parentIndex = i
					}
				} else {
					this.tableDatas[row.parentIndex].children.splice(row.childIndex, 1);
					for (var i = 0; i < this.tableDatas[row.parentIndex].children.length; i++) {
						this.tableDatas[row.parentIndex].children[i].childIndex = i
					}
				}
				this.tableDatas.push({})
				this.tableDatas.splice(this.tableDatas.length - 1, 1)
				for (let item of this.tableDatas) {
					item.questionCount = 0
					if (item.children && item.children.length != 0) {
						for (let val of item.children) {
							item.questionCount += val.questionCount
						}
					}
				}
			},
			// 下一步
			nextTo() {
				if (this.tabIndex == 0) {
					this.$refs['ruleForm'].validate((valid) => {
						if (valid) {
							this.activeName = "second";
							this.tabIndex = Number(this.tabIndex + 1)
						} else {
							console.log('error submit!!');
							return false;
						}
					});
				} else {
					this.activeName = "third";
					this.tabIndex = Number(this.tabIndex + 1)
				}
			},
			//点击图片库
			clickImg(index) {
				this.imgIndex = index
				this.$refs.imgLibrary.show()
			},
			//获取上传图片
			handleImgOk(data) {
				if (this.imgIndex == 2) {
					this.form.specialShow = this.form.specialShow + `<img src='${data}'>`
				} else {
					this.$set(this.form, 'img', data)
				}
			},
			// 上一步
			preTo() {
				switch (Number(this.tabIndex)) {
					case 1:
						this.activeName = "first";
						break;
					case 2:
						this.activeName = "second";
						break;
					case 3:
						this.activeName = "third";
						break;
				}
				this.tabIndex = Number(this.tabIndex - 1)
			},
			handleClick(tab, event) {
				this.tabIndex = tab.index
			},
			//获取省市区树
			async getAllArea() {
				const res = await this.$get('/admin/area/getAllArea')
				if (res.code == 1000) {
					this.areaData = res.data
					this.areaData.unshift({
						adcode: '0',
						name: '默认',
						parentId: 0,
						id: '0'
					})
				}
			},
		}
	}
</script>

<style>
</style>